#include "Counter.h"
using namespace cocos2d;

Counter::Counter()
	:_digit(0)
	,_presenters(0)
{
}

Counter::~Counter()
{
}

bool Counter::init(CCArray* presenters,int digit/*=0*/)
{
	_presenters=CCNode::create();
	for(int i=0;i<10;i++){
		CCNode* node=static_cast<CCNode*>(presenters->objectAtIndex(i));
		int y=node->getContentSize().height*i;
		node->setPosition(0,y);
		_presenters->addChild(node,0,i);
	}
	addChild(_presenters);
	setDigit(digit);
	return true;
}

Counter* Counter::create(CCArray* presenters,int digit/*=0*/)
{
	Counter* pRet=new Counter;
	pRet->init(presenters,digit);
	pRet->autorelease();
	return pRet;
}

void Counter::visit()
{
	glEnable(GL_SCISSOR_TEST);
	CCNode* presenter=_presenters->getChildByTag(_digit);
	CCSize size=presenter->getContentSize();
	CCPoint location=getParent()->convertToWorldSpace(CCPoint(getPosition().x-size.width*0.5,
		getPosition().y-size.height*0.5));
	glScissor(location.x,location.y,size.width,size.height);
	CCNode::visit();
	glDisable(GL_SCISSOR_TEST);
}

void Counter::animation(int digit)
{
	CCNode* presenter=_presenters->getChildByTag(digit);
	CCPoint dest=presenter->getPosition();
	stopActionByTag(0);
	CCMoveTo* moveto=CCMoveTo::create(0.5,CCPoint(0,-dest.y));
	_presenters->runAction(moveto);
}

void Counter::setDigit(int digit)
{
	if(_digit!=digit){
		_digit=digit;
		animation(_digit);
	}
}
